package com.jixi.common.utils;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class ListToStringUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    // 将 List<String> 转换为 JSON 格式的字符串
    public static String convertToJsonString(List<String> list) {
        if (list == null || list.isEmpty()) {
            return "[]";  // 返回空的 JSON 数组
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(list);
        } catch (Exception e) {
            throw new RuntimeException("Error converting List to JSON", e);
        }
    }

    public static List<String> convertJsonToList(String json) {
        try {
            return objectMapper.readValue(json, new TypeReference<List<String>>() {});
        } catch (Exception e) {
            e.printStackTrace();
            return null; // 返回 null 代表转换失败
        }
    }
}
